﻿using BLL;
using System;
using System.Data;
using System.Web.UI.WebControls;
using Utility.Helper;

namespace Thksoft.ParameterSettings
{
    public partial class SetBank : BaseUI.BasePage
    {
        private BaseBLL bsBLL = new BaseBLL();
        private Yx_AccountBLL accountBLL = new Yx_AccountBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.Params["TYPE"] == "API")
                {
                    var requstData = AjaxResult.GetPostData(this.Context);
                    switch (requstData["Type"].NewToObject<string>())
                    {
                        case "GET_BY_CMYID":
                            {
                                var data = accountBLL.GetEntitysByCmyId(requstData["COMPANY_ID"].NewToObject<int>());
                                AjaxResult.Success(this.Context, data);
                            }
                            break;

                        default:
                            break;
                    }
                    return;
                }
                BindCompany();
                this.ddlCompany.SelectedValue = CurrentUserCompanyID.ToString();

                //初始化绑定GridView
                //BindProjectName(false);

                SelectMethod();
            }
        }

        #region 显示绑定公司

        /// <summary>
        /// 绑定公司
        /// </summary>
        public void BindCompany()
        {
            //公司
            DataTable dataCompany = new Sys_CompanyBLL().GetInfoByPId((int)CurrentUserCompanyID);
            //setList(dataCompany, ddlCompany);

            int count;
            string whereStr = @" CMY_ID in (select cp.cmy_id
  from sys_company cp
 start with cp.cmy_id = " + lognUser.USER_COMPANY + @"
connect by prior cp.cmy_id = cp.cmy_parentid) ";
            var dt = new Sys_CompanyBLL().GetEntitys(whereStr, null, 0, 1000, out count);

            ddlCompany.DataSource = dt;
            ddlCompany.DataTextField = "CMY_NAME";
            ddlCompany.DataValueField = "CMY_ID";
            ddlCompany.DataBind();
            ddlCompany.Items.Insert(0, new ListItem("---请选择---", "-1"));
            ddlCompany.SelectedValue = "-1";
        }

        #region DropDownList 显示TreeView效果

        private static DataTable dtCompany = null;

        public void setList(DataTable dt, System.Web.UI.WebControls.DropDownList lb)
        {
            int idx = -1;
            dtCompany = dt;
            for (int n = 0; n < dtCompany.Rows.Count; n++)
            {
                if (dtCompany.Rows[n]["cmy_parentid"].ToString() == new Sys_CompanyBLL().GetInfoById(CurrentUserCompanyID.ToString()).CMY_PARENTID.ToString())
                {
                    idx = idx + 1;
                    addItem(lb, dtCompany.Rows[n]["CMY_ID"].ToString(), dtCompany.Rows[n]["CMY_NAME"].ToString(), idx);
                    idx = idx - 1;
                }
            }
        }

        private void addItem(System.Web.UI.WebControls.DropDownList lb, String sId, String sName, int idx)
        {
            String sn = sName;
            for (int n = 0; n < idx; n++)
            {
                sn = (char)58853 + "" + sn;
            }
            System.Web.UI.WebControls.ListItem it = new ListItem(sn, sId);

            lb.Items.Add(it);

            for (int n = 0; n < dtCompany.Rows.Count; n++)
            {
                if (dtCompany.Rows[n]["cmy_parentid"].ToString() == sId)
                {
                    idx = idx + 1;
                    addItem(lb, dtCompany.Rows[n]["cmy_id"].ToString(), dtCompany.Rows[n]["cmy_name"].ToString(), idx);
                    idx = idx - 1;
                }
            }
        }

        #endregion DropDownList 显示TreeView效果

        #endregion 显示绑定公司

        #region 增，修，查方法

        /// <summary>
        /// 添加公司账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnInsert_Click(object sender, EventArgs e)
        {
            MessageBox.ResponseScript(this, "FORM_INSERT();");
        }

        /// <summary>
        /// 查询公司账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            SelectMethod();
        }

        /// <summary>
        /// 查询方法
        /// </summary>
        private void SelectMethod()
        {
            DataTable dt = null;
            string sql = "";
            if (this.ddlCompany.SelectedValue.ToString() == "-1")
            {
                sql += @" and a.company_id in (SELECT CMY_ID
          FROM SYS_COMPANY T
         START WITH CMY_ID = " + CurrentUserCompanyID + @"
        CONNECT BY PRIOR CMY_ID = CMY_PARENTID)";
            }
            else
            {
                sql += " and a.company_id=" + this.ddlCompany.SelectedValue.ToString() + " ";
            }
            {
                string _sql = @"select a.accounti_id accountId,
       c.cmy_name companyName,
       d.deptname depName,
       decode(a.accounttype, 1, '支出户', 2, '收入户') accType,
       a.accountno accountNo,
       b.c_name openBank,
       decode(a.state, 1, '启用', 0, '停用') state
  from sys_company c, sys_department d, yx_account a,sys_bank b
 where c.cmy_id = d.cmy_id
   and c.cmy_id = a.company_id
   and d.deptid = a.department_id
   and a.n_bank_id=b.n_id";
                if (_sql != "")
                {
                    _sql += sql;
                }
                _sql += "  order by a.company_id,a.department_id ";
                dt = bsBLL.Query(_sql);
            }

            ViewState["WHERE"] = sql;
            //设置分页
            PageIng.CurrentPage = 1;
            PageIng.RowsPerPage = 50;
            //绑定分页数据，默认有条件
            BindData(false);
            grvShow.DataSource = dt;
            grvShow.DataBind();
        }

        /// <summary>
        /// 修改账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                int count = 0;
                for (int i = 0; i < this.grvShow.Rows.Count; i++)
                {
                    if (((CheckBox)this.grvShow.Rows[i].FindControl("chkSelectDel")).Checked == true)
                    {
                        count++;
                        if (count == 1)
                        {
                            string pid = ((HiddenField)grvShow.Rows[i].FindControl("HiddID")).Value.ToString();
                            MessageBox.ResponseScript(this, "FORM_EDIT(\"" + pid + "\");");
                            return;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        #endregion 增，修，查方法

        #region 分页有关数据

        ///// <summary>
        ///// 上一页，下一页
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void grvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    try
        //    {
        //        grvShow.PageIndex = e.NewPageIndex;

        //        SelectMethod();

        //        TextBox tb = (TextBox)grvShow.BottomPagerRow.FindControl("inPageNum");
        //        tb.Text = (grvShow.PageIndex + 1).ToString();
        //    }
        //    catch { }
        //}

        ///// <summary>
        ///// 页数跳转
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        protected void grvShow_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //    try
            //    {
            //        if (e.CommandName == "go")
            //        {
            //            TextBox tb = (TextBox)this.grvShow.BottomPagerRow.FindControl("inPageNum");
            //            int num = Int32.Parse(tb.Text);
            //            GridViewPageEventArgs ea = new GridViewPageEventArgs(num - 1);
            //            grvShow_PageIndexChanging(null, ea);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //    }
        }

        #endregion 分页有关数据

        /// <summary>
        /// 合并相同的列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void grvShow_PreRender(object sender, EventArgs e)
        //{
        //for (int rowIndex = grvShow.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        //{
        //    GridViewRow row = grvShow.Rows[rowIndex];
        //    GridViewRow previousRow = grvShow.Rows[rowIndex + 1];
        //    if (row.Cells[2].Text == previousRow.Cells[2].Text)
        //    {
        //        row.Cells[2].RowSpan = previousRow.Cells[2].RowSpan < 2 ? 2 : previousRow.Cells[2].RowSpan + 1;
        //        previousRow.Cells[2].Visible = false;
        //    }
        //}
        //for (int rowIndex = grvShow.Rows.Count - 2; rowIndex >= 0; rowIndex--)
        //{
        //    GridViewRow row = grvShow.Rows[rowIndex];
        //    GridViewRow previousRow = grvShow.Rows[rowIndex + 1];
        //    if (row.Cells[0].Text == previousRow.Cells[0].Text)
        //    {
        //        row.Cells[0].RowSpan = previousRow.Cells[0].RowSpan < 2 ? 2 : previousRow.Cells[0].RowSpan + 1;
        //        previousRow.Cells[0].Visible = false;
        //    }
        //}
        //}

        /// <summary>
        /// GridView标题排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvShow_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;

            BindProjectName(true);
            //分页绑定数据
            BindData(false);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            string binId = this.hidCompanyId.Value.ToString() == "" ? "" : this.hidCompanyId.Value.ToString();
            string comName = this.ddlCompany.SelectedValue.ToString();

            string sql = "";

            if (binId == "" && comName == "1")
            {
                sql += "";
            }
            else if (comName != "-1")
            {
                sql += " and a.company_id=" + comName;
            }
            else
            {
                sql += " and a.company_id=" + CurrentUserCompanyID;
            }

            DataTable dt = new Yx_AccountBLL().SelectAll(sql);
            DataView view = dt.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            grvShow.DataSource = view;
            grvShow.DataBind();

            //初始化绑定分页，默认无条件
            BindData(false);
        }

        //分页绑定数据
        protected void BindData(bool isFirst)
        {
            if (isFirst)
            {
                PageIng.CurrentPage = 1;
                ViewState["WHERE"] = null;
            }
            string where = ViewState["WHERE"] == null ? null : (string)ViewState["WHERE"];
            string sort = null;
            if (ViewState["SortOrder"] != null)
            {
                sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
            }
            int count;
            DataTable dt = accountBLL.GetData(where, sort, (PageIng.CurrentPage - 1) * PageIng.RowsPerPage, PageIng.RowsPerPage, out count);
            PageIng.Visible = true;
            PageIng.RowsCount = count;
            PageIng.DataSource = dt;
            PageIng.GridViewSource = grvShow;
            PageIng.RowsPerPage = PageIng._rowsPerPage;
            PageIng.Bind();
        }

        //分页
        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }
    }
}